﻿using System.Services;
using System.Threading.Tasks;
using Windows.Devices.Sensors;

namespace System.Sensors
{
    public interface ICompassSensorService : ISensorService<Compass, CompassReading>
    {
    }

    [ExportService("CompassSensorService", "", typeof(ICompassSensorService), int.MaxValue)]
    public class CompassSensorService : SensorServiceBase<Compass, CompassReading>, ICompassSensorService
    {
        public CompassSensorService()
        {
        }

        public override void StartService()
        {
            Sensor = Compass.GetDefault();
            base.StartService();
        }

        public override void Subscribe()
        {
            if (IsSensorAvailable)
                Sensor.ReadingChanged += Sensor_ReadingChanged;

            base.Subscribe();
        }

        public override void Unsubscribe()
        {
            if (IsSensorAvailable)
                Sensor.ReadingChanged -= Sensor_ReadingChanged;

            base.Unsubscribe();
        }

        void Sensor_ReadingChanged(Compass sender, CompassReadingChangedEventArgs args)
        {
            if (EventAggregator != null)
                EventAggregator.Publish<CompassSensorServiceReadingMessage>(new CompassSensorServiceReadingMessage(this, args.Reading));
        }

        protected override async Task<CompassReading> GetSensorData()
        {
            return Sensor.GetCurrentReading();
        }

        public override uint GetMinimumReportInterval()
        {
            return Sensor.MinimumReportInterval;
        }

        public override uint GetReportInterval()
        {
            return Sensor.ReportInterval;
        }

        public override void SetReportInterval(uint value)
        {
            Sensor.ReportInterval = value;
        }
    }

    public class CompassSensorServiceReadingMessage : SensorReadingMessageBase<CompassReading>
    {
        public CompassSensorServiceReadingMessage(object sender, CompassReading value)
            : base(sender, value)
        {
        }
    }
}
